package com.example.reflect;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

/**
 * ClassName:testSomeService
 * Package:com.example.reflect
 * Description:
 *
 * @Author:ZhangXin
 * @Create:2023/5/9-15:07
 * @Version:v1.0
 */
public class testSomeService {

    @Test
    public void reflect3() throws Exception {
        Class<?> aClass = Class.forName("com.example.reflect.SomeService");
        Method doSome = aClass.getDeclaredMethod("doSome", String.class);

        Constructor<?> constructor = aClass.getDeclaredConstructor();
        Object instance = constructor.newInstance();

        Object invoke = doSome.invoke(instance, "李四");
        System.out.println(invoke);
    }

    @Test
    public void reflect2() throws Exception {
        Class<?> aClass = Class.forName("com.example.reflect.SomeService");
        Method doSome = aClass.getDeclaredMethod("doSome");

        Constructor<?> constructor = aClass.getDeclaredConstructor();
        Object instance = constructor.newInstance();

        Object invoke = doSome.invoke(instance);

        System.out.println(invoke);
    }

    @Test
    public void reflect() throws Exception {
        //使用反射机制
        //获取类
        Class<?> aClass = Class.forName("com.example.reflect.SomeService");
        //获取类
        Method doSome = aClass.getDeclaredMethod("doSome", String.class, int.class);
        //调用方法(四要素：调用哪个对象,哪个方法,传什么参数,返回什么值)
        Constructor<?> constructor = aClass.getDeclaredConstructor();
        Object instance = constructor.newInstance();
        Object invoke = doSome.invoke(instance, "李四", 24);
        System.out.println(invoke);
    }

    @Test
    public void test() {
        //不使用反射机制
        SomeService someService = new SomeService();
        someService.doSome();
        someService.doSome("李四");
        someService.doSome("李四", 20);
    }
}
